package blackjack;

import java.util.ArrayList;
import java.util.Random;

public class Deck {
	Hand player;
	ArrayList<Card> deck = new ArrayList<Card>();
	int size = 0;

	public Deck() {
		for (int i = 0; i < 4; i++) {
			for (int j = 2; j < 15; j++) {
				deck.add(new Card(i, j));
				size++;
			}
		}
	}

	public Card hit() {
		size--;
		return deck.remove(0);

	}

	public Deck(int howMany) {
		howMany*=4;
		for (int i = 0; i < howMany; i++) {
			for (int j = 2; j < 15; j++) {
				deck.add(new Card(i, j));
				size++;
			}
		}
	}
 public void printCardValues()
 {
	 System.out.println(size);
	 for (int i = 0; i < size;i++)
		 System.out.println(deck.get(i).cardValue);
 }

	public String toString() {
		String ret = "";
		for (int i = 0; i < deck.size(); i++) {
			ret += deck.get(i) + "\n";
		}
		return ret;
	}

	void shuffle() {
		ArrayList<Card> oldDeck = deck;
		deck = new ArrayList<Card>();
		Random random = new Random();
		int shuffleIndex;

		int i = 0;
		int deckSize = oldDeck.size();
		while (i < deckSize) {
			shuffleIndex = random.nextInt(deckSize);
			int index = find(oldDeck, shuffleIndex);
			if (index >= 0) {
			
				deck.add(oldDeck.remove(index));
				
				i++;
			}
		}
	}

	private int find(ArrayList<Card> oldDeck, int value) {
		int middle, first, last;
		first = 0;
		last = oldDeck.size() - 1;

		while (first < last) {
			middle = (first + last) / 2;
			if (oldDeck.get(middle).cardValue == value) {
				return middle;
			}
			if (oldDeck.get(middle).cardValue > value) {
				last = middle - 1;
			}
			if (oldDeck.get(middle).cardValue < value) {
				first = middle + 1;
			}
		}
		if (oldDeck.get(first).cardValue != value)
			return -1;
		return first;

	}
}
